<script setup lang="ts" name="adjustForm">
import { startWorkFlow } from '@/api/workflow/task';
import { StartProcessBo } from '@/api/workflow/workflowCommon/types';
import SubmitVerify from '@/components/Process/submitVerify.vue';
import ApprovalRecord from '@/components/Process/approvalRecord.vue';
import { BudgetSubjectVO } from '@/api/budget/budgetSubject/types';
import { AdjustDetailForm, AdjustDetailVO, AdjustForm, AdjustQuery } from '@/api/fill/adjust/types';
import { addAdjust, deleteDetail, getAdjust, getAdjustDetail, listDetail, saveDetail, updateDetail } from '@/api/fill/adjust';
import { defaultYard, types } from '@/hooks/useCommon';
import { getListSubject } from '@/api/budget/budgetSubject';
import { checkConfig } from '@/api/budget/actAdjustConfig';
import { reactive } from 'vue';
import { TableEnum } from '@/enums/business/TableEnum';

/**季度*/
const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const { yard_type, adjust_type, budget_type } = toRefs<any>(proxy?.useDict('yard_type', 'adjust_type', 'budget_type'));
const showSearch = reactive({
  search: true,
  icon: 'Top',
  desc: '收起'
});
const clickQuery = () => {
  showSearch.search = !showSearch.search;
  if (!showSearch.search) {
    showSearch.icon = 'Bottom';
    showSearch.desc = '展开';
  } else {
    showSearch.icon = 'Top';
    showSearch.desc = '收起';
  }
};
/*主表表单*/
const initFormData: AdjustForm = {
  id: undefined,
  deptCode: undefined,
  deptName: undefined,
  yardCode: undefined,
  year: undefined,
  adjustType: undefined,
  budgetType: undefined,
  status: undefined
};

/*主表表单*/
const form = ref<AdjustForm>(initFormData);
/*主表添加校验规则*/
const rules = {
  adjustType: [{ required: true, message: '请选择调整类型', trigger: 'blur' }],
  budgetType: [{ required: true, message: '请选择预算类型', trigger: 'blur' }],
  yardCode: [{ required: true, message: '请选择院区', trigger: 'blur' }]
};

/**季度*/
const quarterOptions = [
  {
    value: '1',
    label: '第一季度'
  },
  {
    value: '2',
    label: '第二季度'
  },
  {
    value: '3',
    label: '第三季度'
  },
  {
    value: '4',
    label: '第四季度'
  }
];

const subjectList = ref<BudgetSubjectVO[]>([]);

const theSubjectList = ref<BudgetSubjectVO[]>([]);

// 选中预算科目
const getTheSubjectList = async (type: string) => {
  theSubjectList.value = [];
  switch (type) {
    case 'business':
      subjectList.value.map((item) => {
        if (item.type === 'business_function' || item.type === 'both_function') {
          theSubjectList.value.push(item);
        }
      });
      break;
    case 'manage':
      subjectList.value.map((item) => {
        if (item.type === 'manage_function' || item.type === 'both_function') {
          theSubjectList.value.push(item);
        }
      });
      break;
  }
};

/**预算科目列表下拉*/
const getSubjectList = async () => {
  getListSubject().then((res) => {
    subjectList.value = res.data;
  });
};

const buttonLoading = ref(false);

/** 表单重置 */
const reset = () => {
  submitButtonShow.value = true;
  form.value = { ...initFormData };
  adjustFormRef.value?.resetFields();
};

const loading = ref(false);

const adjustFormRef = ref<ElFormInstance>();
/** 提交按钮 */
const submitForm = () => {
  try {
    adjustFormRef.value?.validate(async (valid: boolean) => {
      if (valid) {
        if (adjustDetailList.value.length === 0) {
          proxy?.$modal.msgError('请添加预算调整明细');
          return;
        }
        buttonLoading.value = true;
        await addAdjust(form.value)
          .then((res) => {
            form.value = res.data;

            // proxy?.$modal.msgSuccess("操作成功");
            // 提交工作流程
            handleStartWorkFlow(res.data);
          })
          .finally(() => (buttonLoading.value = false));
      }
    });
  } finally {
    buttonLoading.value = false;
  }
};
/*调整金额*/
const adjustTotal = ref(0);
/*合计*/
const getSummary = (param: any) => {
  const { columns, data } = param;
  const sums = [];
  columns.forEach((column: any, index: number) => {
    if (index === 0) {
      sums[index] = '合计';
      return;
    }

    if (column.property === 'applyMoney') {
      const values = data.map((item: any) => {
        // 确保转换为数字，处理空值/非数值情况
        const num = Number(item[column.property]);
        return isNaN(num) ? 0 : num;
      });

      // 计算合计值并保留两位小数
      const total = values.reduce((prev: number, curr: number) => prev + curr, 0);
      sums[index] = total.toFixed(2); // 转换为保留两位小数的字符串
      adjustTotal.value = total.toFixed(2);
      console.log('adjustTotal.value', adjustTotal.value);
    } else {
      // 非金额列留空
      sums[index] = '';
    }
  });

  return sums;
};

/*总计*/
const total = ref(0);
/*明细列表查询*/
const queryDetailDTO = ref<AdjustQuery>({
  pageNum: 1,
  pageSize: 10,
  actId: undefined
});

/*明细列表*/
const adjustDetailList = ref<AdjustDetailVO[]>([]);
/*明细表单*/
const initDetailFormData = {
  actAdjust: undefined,
  subjectName: undefined,
  subjectCode: undefined,
  applyMoney: undefined,
  reason: undefined,
  adjustType: undefined,
  quarter:undefined,
  id: undefined
};
/** 调整科目明细 */
const detailFrom = ref<AdjustDetailForm>(initDetailFormData);

/*明细表单校验规则*/
const rulesDetail = {
  subjectCode: [{ required: true, message: '预算科目不能为空', trigger: 'blur' }],
  adjustType: [{ required: true, message: '调整方式不能为空', trigger: 'blur' }],
  quarter: [{ required: true, message: '调整季度不能为空', trigger: 'blur' }],
  reason: [{ required: true, message: '调整原因不能为空', trigger: 'blur' }],
  applyMoney: [
    { required: true, message: '申请金额不能为空', trigger: 'blur' },
    {
      validator: (rule: any, value: any, callback: any): void => {
        if (value > 100000000) {
          detailFrom.value.applyMoney = 100000000;
          callback(new Error('申请金额不能大于100000000'));
        } else {
          callback();
        }
      },
      trigger: 'blur'
    }
  ]
};

/**选中的预算科目*/
const selectSubject = (value: any) => {
  detailFrom.value.subjectName = subjectList.value.find((item) => item.subjectCode === value).subjectName;
};

/** 查询预算调整主列表 */
const getDetailList = () => {
  loading.value = true;

  queryDetailDTO.value.actId = form.value.id;
  listDetail(queryDetailDTO.value)
    .then((res) => {
      adjustDetailList.value = res.data.records;
      total.value = res.data.total;
    })
    .finally(() => (loading.value = false));
};

/**详情弹窗*/
const dialog = reactive<DialogOption>({
  visible: false,
  title: '添加明细'
});

/** 新增按钮操作 */
const handleAdd = () => {
  if (form.value.budgetType === undefined || form.value.budgetType === '' || form.value.budgetType === null) {
    proxy?.$modal.msgError('请选择预算类型');
    return;
  }
  if (form.value.adjustType === undefined || form.value.adjustType === '' || form.value.adjustType === null) {
    proxy?.$modal.msgError('请选择调整类型');
    return;
  }
  resetDetail();
  getTheSubjectList(form.value.budgetType);
  dialog.title = '新增明细';
  dialog.visible = true;
};
/** 编辑按钮操作 */
const handleUpdate = async (row?: any) => {
  resetDetail();
  await getTheSubjectList(form.value.budgetType);

  getAdjustDetail(row?.id).then((res) => {
    Object.assign(detailFrom.value, res.data);
    detailFrom.value.adjustType = res.data.applyMoney > 0 ? 'up' : 'down';
  });

  dialog.title = '编辑明细';
  dialog.visible = true;

  console.log(detailFrom.value);
};
/** 删除按钮操作 */
const handleDelete = async (row?: any) => {
  await proxy?.$modal
    .confirm('是否确认删除选中的数据项？')
    .then(() => deleteDetail(row?.id))
    .finally(() => (loading.value = false));
  getDetailList();
  proxy?.$modal.msgSuccess('删除成功');
};
const detailFormRef = ref<ElFormInstance>();

//重置
function resetDetail() {
  detailFrom.value = { ...initDetailFormData };
  detailFormRef.value?.resetFields();
}

/*取消*/
const cancelDetail = () => {
  resetDetail();
  dialog.visible = false;
};

/*保存明细*/
const submitDetailForm = () => {
  detailFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      buttonLoading.value = true;
      if (detailFrom.value.id) {
        updateDetail(detailFrom.value)
          .then((res) => {
            proxy?.$modal.msgSuccess('修改成功');
            dialog.visible = false;
            //刷新列表
            getDetailList();
          })
          .finally(() => (buttonLoading.value = false));
      } else {
        detailFrom.value.actAdjust = form.value;
        saveDetail(detailFrom.value)
          .then((res) => {
            form.value.id = res.data;
            proxy?.$modal.msgSuccess('新增成功');
            dialog.visible = false;
            //刷新列表
            getDetailList();
          })
          .finally(() => (buttonLoading.value = false));
      }
    }
  });
};

//提交组件
const submitVerifyRef = ref<InstanceType<typeof SubmitVerify>>();
//审批记录组件
const approvalRecordRef = ref<InstanceType<typeof ApprovalRecord>>();
const submitFormData = ref<StartProcessBo>({
  businessKey: '',
  tableName: '',
  variables: {}
});
const taskVariables = ref<Record<string, any>>({});
//提交申请
const handleStartWorkFlow = async (data: AdjustForm) => {
  try {
    submitFormData.value.tableName = TableEnum.FILL_ACT_ADJUST;
    submitFormData.value.businessKey = data.id;
    //流程变量
    taskVariables.value = {
      entity: data,
      purchaseDeptName: '/',
      deptName: data.deptName,
      deptCode: data.deptCode,
      adjustType: data.adjustType,
      adjustTotal: Math.abs(adjustTotal.value)
      // userList: [],
      // userList2: [],
    };
    submitFormData.value.variables = taskVariables.value;
    const resp = await startWorkFlow(submitFormData.value);

    if (submitVerifyRef.value) {
      buttonLoading.value = false;
      submitVerifyRef.value.openDialog(resp.data.taskId);
    }
  } finally {
    buttonLoading.value = false;
  }
};
//审批记录
const handleApprovalRecord = () => {
  approvalRecordRef.value.init(form.value.id);
};
//提交回调
const submitCallback = async () => {
  await proxy.$tab.closePage(proxy.$route);
  proxy.$router.go(-1);
};

//返回
const goBack = () => {
  proxy.$tab.closePage(proxy.$route);
  proxy.$router.go(-1);
};
//审批
const approvalVerifyOpen = async () => {
  submitVerifyRef.value.openDialog(routeParams.value.taskId);
};

//校验提交按钮是否显示
const submitButtonShow = ref(true);

//校验审批按钮是否显示
const approvalButtonShow = computed(() => {
  return routeParams.value.type === 'approval' && form.value.status && form.value.status === 'waiting';
});
//组件是否展示
const show = ref(true);
//操作按钮是否展示
const operation = ref(true);
//路由参数
const routeParams = ref<Record<string, any>>({});

/** 获取详情 */
const getInfo = () => {
  //查询主表详情
  nextTick(async () => {
    getAdjust(routeParams.value.id)
      .then((res) => {
        Object.assign(form.value, res.data);
        submitButtonShow.value =
          routeParams.value.type === 'update' &&
          (form.value.status === null || form.value.status === 'draft' || form.value.status === 'cancel' || form.value.status === 'back');
      })
      .then(() => {
        //查询明细列表
        getDetailList();
      });
  });
};

const checkConfigFlag = ref(false);

const getCheckConfig = () => {
  checkConfig('1').then((res) => {
    checkConfigFlag.value = res.data;
  });
};

const handleConfig = (value: string) => {
  if (value === 'metaphase') {
    checkConfig('1').then((res) => {
      checkConfigFlag.value = res.data;
    });
    if (!checkConfigFlag.value) {
      form.value.adjustType = undefined;
      proxy?.$modal.msgError('还未到中期调整时间');
    }
  }
};
onMounted(() => {
  getCheckConfig();

  getSubjectList();
  nextTick(async () => {
    routeParams.value = proxy.$route.query;
    reset();
    loading.value = false;
    if (routeParams.value.type === 'update' || routeParams.value.type === 'view' || routeParams.value.type === 'approval') {
      show.value = false;
      getInfo();
      operation.value = !(routeParams.value.type === 'view' || routeParams.value.type === 'approval');
    } else if (routeParams.value.type === 'add') {
      form.value = {
        year: routeParams.value.year,
        deptName: routeParams.value.deptName,
        deptCode: routeParams.value.deptCode,
        yardCode: defaultYard,
        status: 'draft'
      };
    }
  });
});

// 处理值变化的核心逻辑
const adjustValue = (type: string, value: number | null): number | null => {
  if (value === null || value === 0) return value;
  const absoluteValue = Math.abs(value);
  return type === 'up' ? absoluteValue : -absoluteValue;
};

watch(
  () => detailFrom.value.adjustType,
  (newType) => {
    // 当调整类型发生变化时，自动转换金额符号
    if (!newType || detailFrom.value.applyMoney === null) return;

    detailFrom.value.applyMoney = adjustValue(newType, detailFrom.value.applyMoney);
  }
);

watch(
  () => detailFrom.value.applyMoney,
  (newVal) => {
    // 当用户直接输入时，强制符号与当前类型一致
    if (newVal === null || !detailFrom.value.adjustType) return;

    const shouldBe = adjustValue(detailFrom.value.adjustType, newVal);

    if (newVal !== shouldBe) {
      detailFrom.value.applyMoney = shouldBe;
    }
  }
);
</script>

<template>
  <el-card shadow="hover" style="height: 90vh">
    <div>
      <el-card shadow="never">
        <div class="top-nav">
          <div>
            <el-form ref="adjustFormRef" :model="form" :inline="true">
              <el-form-item label="年份" prop="year">
                <el-date-picker date-format="YYYY" value-format="YYYY" type="year" v-model="form.year" disabled />
              </el-form-item>
              <el-form-item label="预算部门" prop="deptName">
                <el-input :placeholder="form.deptName" clearable disabled />
              </el-form-item>
            </el-form>
          </div>

          <div>
            <el-button v-if="submitButtonShow" :loading="buttonLoading" type="success" @click="submitForm()" icon="CircleCheck">提交</el-button>
            <el-button v-if="approvalButtonShow" :loading="buttonLoading" type="primary" @click="approvalVerifyOpen" icon="Promotion">审批</el-button>
            <el-button
              v-if="form && form.id && form.status !== null && form.status !== 'draft'"
              type="primary"
              @click="handleApprovalRecord"
              icon="View"
            >
              流程进度
            </el-button>
            <el-button type="danger" @click="goBack()" style="margin-right: 50px">
              <svg-icon icon-class="back" />
              <span style="margin-left: 5px">返回</span></el-button
            >
          </div>
        </div>

        <div v-show="showSearch.search">
          <div class="form-class">
            <el-form ref="adjustFormRef" :model="form" :rules="show ? rules : null" :inline="true">
              <br />
              <el-form-item label="院区" prop="yardCode">
                <el-select v-model="form.yardCode" :disabled="!show">
                  <el-option v-for="dict in yard_type" :key="dict.value" :label="dict.label" :value="dict.value" />
                </el-select>
              </el-form-item>
              <el-form-item label="预算类型" prop="budgetType" label-width="80">
                <el-select
                  v-model="form.budgetType"
                  clearable
                  :disabled="!show"
                  @change="
                    (value: string) => {
                      getTheSubjectList(value);
                    }
                  "
                >
                  <el-option v-for="dict in budget_type" :key="dict.value" :label="dict.label" :value="dict.value" />
                </el-select>
              </el-form-item>
              <el-form-item label="调整类型" prop="adjustType" label-width="80">
                <el-select
                  v-model="form.adjustType"
                  clearable
                  :disabled="!show"
                  :default-first-option="true"
                  @change="
                    (value: string) => {
                      handleConfig(value);
                    }
                  "
                >
                  <el-option v-for="dict in adjust_type" :key="dict.value" :label="dict.label" :value="dict.value" />
                </el-select>
              </el-form-item>
            </el-form>
          </div>
        </div>
      </el-card>

      <el-card shadow="never">
        <div class="container-main">
          <div class="nav-class">
            <div>
              <span class="nav-span">预算调整科目明细</span>
              <el-button type="success" icon="Plus" @click="handleAdd" class="btn btn-add" v-if="operation">新增</el-button>
            </div>
            <div>
              <el-button type="info" :icon="showSearch.icon" @click="clickQuery" style="margin-right: 30px" class="btn"
                >{{ showSearch.desc }}
              </el-button>
            </div>
          </div>
          <div>
            <el-table border v-loading="loading" :data="adjustDetailList" show-summary :summary-method="getSummary" class="enhanced-table">
              <el-table-column label="主键id" align="center" prop="id" v-if="false" />
              <el-table-column label="预算科目编码" align="center" prop="subjectCode" show-overflow-tooltip width="170" />
              <el-table-column label="预算科目" align="center" prop="subjectName" show-overflow-tooltip width="230" />
              <el-table-column label="调整季度" align="center" prop="quarter" width="200" >
                <template #default="scope">
                  <dict-tag :options="quarterOptions" :value="scope.row.quarter" />
                </template>
              </el-table-column>
              <el-table-column label="申请金额（万元）" align="center" prop="applyMoney" width="180" />
              <el-table-column label="调整原因" align="center" prop="reason" show-overflow-tooltip width="300" />
              <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="120">
                <template #default="scope"  v-if="operation">
                  <el-tooltip content="编辑" placement="top">
                    <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['fill:adjust:edit']"></el-button>
                  </el-tooltip>
                  <el-tooltip content="删除" placement="top">
                    <el-button link type="danger" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['fill:adjust:remove']"></el-button>
                  </el-tooltip>
                </template>
              </el-table-column>
            </el-table>
            <pagination
              v-show="total > 0"
              :total="total"
              v-model:page="queryDetailDTO.pageNum"
              v-model:limit="queryDetailDTO.pageSize"
              @pagination="getDetailList"
            />
          </div>
        </div>
      </el-card>

      <!-- 添加明细对话框 -->
      <el-dialog :title="dialog.title" v-model="dialog.visible" style="width: 550px" append-to-body>
        <el-form ref="detailFormRef" :model="detailFrom" :rules="rulesDetail" label-width="80px">
          <el-form-item label="预算科目" prop="subjectCode">
            <el-select v-model="detailFrom.subjectCode" placeholder="请选择" @change="selectSubject" filterable>
              <el-option
                v-for="item in theSubjectList"
                :key="item.subjectCode"
                :label="item.subjectCode + ' - ' + item.subjectName"
                :value="item.subjectCode"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="调整季度" prop="quarter">
            <el-select v-model="detailFrom.quarter" placeholder="请选择">
              <el-option v-for="dict in quarterOptions" :key="dict.value" :label="dict.label" :value="dict.value"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="调整方式" prop="adjustType">
            <el-select v-model="detailFrom.adjustType" placeholder="请选择">
              <el-option v-for="dict in types" :key="dict.key" :label="dict.label" :value="dict.key"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="申请金额" prop="applyMoney">
            <el-input v-model="detailFrom.applyMoney" type="number" placeholder="请输入申请金额">
              <template #append><span style="font-weight: bolder; color: dodgerblue">万元</span></template>
            </el-input>
          </el-form-item>
          <el-form-item label="调整原因" prop="reason">
            <el-input
              v-model="detailFrom.reason"
              placeholder="请输入内容"
              type="textarea"
              style="width: 800px"
              maxlength="500"
              show-word-limit
              :autosize="{ minRows: 4 }"
            />
          </el-form-item>
        </el-form>
        <template #footer>
          <div class="dialog-footer">
            <el-button :loading="buttonLoading" type="primary" @click="submitDetailForm">确 定</el-button>
            <el-button @click="cancelDetail">取 消</el-button>
          </div>
        </template>
      </el-dialog>
      <!-- 提交组件 -->
      <submitVerify ref="submitVerifyRef" :task-variables="taskVariables" @submit-callback="submitCallback" />
      <!-- 审批记录 -->
      <approvalRecord ref="approvalRecordRef" />
    </div>
  </el-card>
</template>

<style scoped lang="scss">
@import '@/assets/styles/common-style';

.container-main {
  margin-left: 10px;
  width: 75em;
}

.form-class {
  box-shadow: 0 1px 2px #f8f8ff;
  padding: 2px 0;
}

.nav-class {
  height: 50px;
  border-radius: 5px 5px 0 0;
  background-color: #f8f8ff;
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.nav-span {
  margin-left: 20px;
  text-align: center;
  line-height: 50px;
  font-weight: bolder;
  font-size: 20px;
}

.btn-add {
  margin-left: 30px;
}
</style>
